<?php

namespace app\system\controller\category;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use ba\Tree;
use hehe\Str;
use hehe\Trade;
use think\facade\Db;


class Industry extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['name'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\category\Industry();

        $this->tree = Tree::instance();

        $isTree = $this->request->param('isTree', true);
        $this->initValue = $this->request->get('initValue/a', []);
        $this->initValue = array_filter($this->initValue);
        $this->keyword = $this->request->request('quickSearch', '');

        // 有初始化值时不组装树状（初始化出来的值更好看）
        $this->assembleTree = $isTree && !$this->initValue;
    }




    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }


        if(empty($this->request->param('keyword'))){
            $where[] = ['pid', '=', $this->request->param('pid')];
        }else{
            if(empty($this->request->param('pid'))){
                $keyword = trim($this->request->param('keyword'));
                $where[] = ['name', 'like', "%{$keyword}%"];
            }else{
                $where[] = ['pid', '=', $this->request->param('pid')];
            }

        }

        $res = $this->model->with(['hasChildren'])->where($where)->select();


        $this->success('', [
//            'list' => $this->getData(),
            'list' => $res,
            'remark' => get_route_remark(),
        ]);
    }

    public function add(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $data['type'] = empty($data['type']) ? null : implode(',', $data['type']);

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }


    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $data['type'] = empty($data['type']) ? null : implode(',', $data['type']);
//            print_r($data);die;
            $result = false;
            $this->model->startTrans();
            try {
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
        $row = $row->toArray();
        if(!empty($row['files'])){
            $row['files'] =  json_decode($row['files'], true);
            $files = [];
            foreach($row['files'] as $val){
                $files[] = $val['name'];
            }
            $row['files'] = $files;
        }

        $row['type'] = empty($row['type']) ? [] : explode(',', $row['type']);

        $this->success('', [
            'row' => $row
        ]);
    }



    /**
     * 重写select方法
     * @throws Throwable
     */
    public function select(): void {
        $data = $this->getData([]);

        if ($this->assembleTree) {
            $data = $this->tree->assembleTree($this->tree->getTreeArray($data, 'name'));
        }
        $this->success('', [
            'options' => $data
        ]);
    }


    public function getData($where = []): array {
        $pk = $this->model->getPk();
        $initKey = $this->request->get("initKey/s", $pk);



        if ($this->keyword) {
            $keyword = explode(' ', $this->keyword);
            foreach ($keyword as $item) {
                $where[] = ['name', 'like', '%' . $item . '%'];
            }
        }

        if ($this->initValue) {
            $where[] = [$initKey, 'in', $this->initValue];
        }

//        print_r($where);die;

        $result = $this->model
            ->where($where)
            ->order('weigh desc,id asc')
            ->select()->toArray();

        // 如果要求树状，此处先组装好 children
        $list =  $this->assembleTree ? $this->tree->assembleChild($result) : $result;
        return $list;
    }





    /**
     * 删除
     * @param array $ids
     * @throws Throwable
     */
    public function del(array $ids = []): void
    {

        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }

        $where             = [];
        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $where[] = [$this->dataLimitField, 'in', $dataLimitAdminIds];
        }

        $pk      = $this->model->getPk();
        $where[] = [$pk, 'in', $ids];

        $count = 0;
        $data  = $this->model->where($where)->select();
        $this->model->startTrans();
        try {
            foreach ($data as $v) {
                $count += $v->delete();
            }
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }






























}